# -*- coding: utf-8 -*-
# flake8: noqa
from os import path
from sys import argv

from qiniu import Auth, put_file, etag, BucketManager
import datetime

# 需要填写你的 Access Key 和 Secret Key
access_key = ''
secret_key = ''
# 构建鉴权对象
q = Auth(access_key, secret_key)
# 要上传的空间
bucket_name = ''


def upload(file_path, storage_type=0, upload_name=None):
    # 上传到七牛后保存的文件名
    if upload_name is None:
        upload_name = path.basename(file_path)
    now = datetime.datetime.now()
    key = "%s/%s" % (now.strftime('%Y-%m-%d/%H-%M'), upload_name)
    # 生成上传 Token，可以指定过期时间等
    token = q.upload_token(bucket_name, key, 3600)
    # 要上传文件的本地路径
    local_file = file_path
    ret, info = put_file(token, key, local_file)
    print(info)
    assert ret['key'] == key
    assert ret['hash'] == etag(local_file)

    if storage_type > 0:
        bucket = BucketManager(q)
        ret, info = bucket.change_type(bucket_name, key, storage_type)  # 1表示低频存储，0是标准存储
        print(info)


if __name__ == '__main__':
    if len(argv[1:]) == 0:
        print("please pass the file path for upload")
    elif len(argv) > 1:
        filename = argv[1]
        sto_type = int(argv[2]) if (argv[2] is not None and int(argv[2]) < 2) else 0
        if path.isfile(filename):
            upload(filename, sto_type)
        else:
            print(filename + " not exist")
